package edu.calpoly.android.lab1adiel;

//import android.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import edu.calpoly.android.lab1adiel.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class ButtonListener extends Activity implements OnClickListener {

	android.widget.EditText _textField;
	private static final int CAMERA_PIC_REQUEST = 1337; 
	private Mat _Gray;
	private Mat _sepiaKernal;
	private ImageProcess _ImageProcess;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		this._ImageProcess = new ImageProcess();
		this._Gray = new Mat();
		_sepiaKernal = new Mat(4, 4, CvType.CV_32F);
		_sepiaKernal.put(0, 0, /* R */0.189f, 0.769f, 0.393f, 0f);
		_sepiaKernal.put(1, 0, /* G */0.168f, 0.686f, 0.349f, 0f);
		_sepiaKernal.put(2, 0, /* B */0.131f, 0.534f, 0.272f, 0f);
		_sepiaKernal.put(3, 0, /* A */0.000f, 0.000f, 0.000f, 1f);
		this.setContentView(R.layout.name_getter);
		this._textField = (EditText) this.findViewById(R.id.enterNameTextField);
		android.widget.Button tButton = (Button) this.findViewById(R.id.cameraButton);
		tButton.setOnClickListener(this);
	}
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		if (requestCode == CAMERA_PIC_REQUEST) {  
			try {
				Bitmap bitmap = (Bitmap) data.getExtras().get("data");
				this._Gray = Utils.bitmapToMat(bitmap);
				//int i = this._Gray.channels();
				//Sepia Transform
				//Core.transform(this._Gray, this._Gray, _sepiaKernal);

				Mat tMat = thresholdPicture();
				Bitmap tOutBitmap = Bitmap.createBitmap(tMat.cols(),tMat.rows(),Bitmap.Config.ARGB_8888);
				if (Utils.matToBitmap(tMat, tOutBitmap))
				{
					
					//new Picture
					this.setContentView(R.layout.picture_display);
					Drawable drawable =new BitmapDrawable(getResources(),tOutBitmap);
					SurfaceView tSurfaceView = (SurfaceView) findViewById(R.id.surfaceView1);  
					tSurfaceView.setBackgroundDrawable(drawable);//TODO: not working if we picture vertically
					
					//Old Picture
					tOutBitmap = openPicture();//Added Code
					drawable =new BitmapDrawable(getResources(),tOutBitmap);
					tSurfaceView = (SurfaceView) findViewById(R.id.surfaceView2);  
					tSurfaceView.setBackgroundDrawable(drawable);//TODO: not working if we picture vertically					
					if(savePicture(tOutBitmap)){
						Log.i("OpenCV", "Success in saving picture to SDCard");
					}
					else{
						Log.i("OpenCV", "Success in saving picture to SDCard");
					}
				}
				else{
					Log.i("OpenCV", "Failed convert mat to bitmap");
				}
			}
			catch (Exception e) {
				Log.i("OpenCV", "Failed to Use OpenCV" + e.getMessage());
			}
		}  
	}  

	//	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		String tInputText = this._textField.getText().toString();
		//android.provider.MediaStore.ACTION_IMAGE_CAPTURE
		Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); 
		//android.content.Intent tIntentClass = new Intent(this, HelloWorld.class);
		//tIntentClass.putExtra("userName", tInputText);
		//this.startActivity(tIntentClass);


	}

	private Bitmap openPicture(){
		
		Bitmap tBitmap = null;
		
		try{
			tBitmap  = BitmapFactory.decodeResource(getResources(), R.drawable.er);
			//tBitmap = this._ImageProcess.iterateOverABitmap(tBitmap);
		}
		catch (Exception e) {
			// TODO: handle exception
			Log.i("OpenCV","Couldn't get Bitmap from resource file" + e.getMessage());
		}
		return tBitmap;
	}
	
	private boolean savePicture(Bitmap bitmap){
		
		boolean tAns = true;
		String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
		OutputStream outStream = null;
		File file = new File(extStorageDirectory, "er.PNG");
		try {
			outStream = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
			outStream.flush();
			outStream.close();

			Toast.makeText(ButtonListener.this, "Saved", Toast.LENGTH_LONG).show();

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			tAns = false;
			e.printStackTrace();
			Toast.makeText(ButtonListener.this, e.toString(), Toast.LENGTH_LONG).show();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			tAns = false;
			e.printStackTrace();
			Toast.makeText(ButtonListener.this, e.toString(), Toast.LENGTH_LONG).show();
		}
		return tAns;
	}

	private Mat thresholdPicture(){
		//Mat tMatThreshed = new Mat(this._Gray.rows(),this._Gray.cols(),CvType.CV_8UC4);
		double tThreshold = 50;
		Mat tMatThreshed = new Mat();

		Imgproc.cvtColor(this._Gray, tMatThreshed, Imgproc.COLOR_RGBA2GRAY);
		//Imgproc.threshold(tMatThreshed, tMatThreshed, 50, 50,Imgproc.THRESH_BINARY);
		Mat mT2 = new Mat();
		try{
			//Blurring the image
			//Imgproc.GaussianBlur(tMatThreshed, tMatThreshed, new Size(3,3), 0);
			Imgproc.bilateralFilter(tMatThreshed, mT2, 5, 64, 64);
			tMatThreshed = mT2;
			//Adaptive threshold
			Imgproc.adaptiveThreshold(tMatThreshed, tMatThreshed, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C,Imgproc.THRESH_BINARY , 3, 3);
			
			//Imgproc.Canny(tMatThreshed,tMatThreshed,32,64);
			//Core.bitwise_not(tMatThreshed, tMatThreshed);
			
			//Dilate the image
			//Mat tKernel = Imgproc.getStructuringElement(Imgproc.MORPH_DILATE, new Size(3,3), new Point(0,0));
			//Imgproc.dilate(tMatThreshed, tMatThreshed, tKernel);
		}
		catch(Exception e){
			Log.i("OpenCV","Couldn't preform adaptiveThreshold because" + e.getMessage());
		}
		Imgproc.cvtColor(tMatThreshed, tMatThreshed, Imgproc.COLOR_GRAY2BGRA,4);
		return tMatThreshed;
	}

}
